package com.tanhua.dubbo.api;


import com.tanhua.dubbo.mongo.MovementApi;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;


@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;

    //发布动态
    public void publish(Movement movement) {
        //1、保存动态详情
        try {
            //设置PID
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);
            //调用异步程序保存用户信息
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            //忽略事务处理
            e.printStackTrace();
        }
    }

    /**
     * 查询我的动态
     * @param userId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0,movements);
    }

    /**
     * 查询好友动态
     * @param friendId
     * @param page
     * @param pagesize
     * @return
     */
    @Override
    public List<Movement> findFriendMovements(Long friendId, Integer page, Integer pagesize) {
        //根据用户id查询时间线表
        Query query=Query.query(Criteria.where("friendId").in(friendId))
                         .skip((page-1)*pagesize).limit(pagesize)
                         .with(Sort.by(Sort.Order.desc("created")));
        List<MovementTimeLine> movementTimeLines = mongoTemplate.find(query, MovementTimeLine.class);
        //根据动态id查询动态
        List<ObjectId> movementIds = movementTimeLines.stream()
                                  .map(item -> item.getMovementId())
                                  .collect(Collectors.toList());
        Query movementQuery = Query.query(Criteria.where("id").in(movementIds));
        //返回查询到的好友动态数据
        return mongoTemplate.find(movementQuery,Movement.class);
    }

    /**
     * 随机推荐动态
     * @param counts
     * @return
     */
    @Override
    public List<Movement> randomMovements(Integer counts) {
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,
                Aggregation.sample(counts));

        AggregationResults<Movement> movements = mongoTemplate.aggregate(aggregation,Movement.class);

        return movements.getMappedResults();
    }

    /**
     * 指定查询动态
     * @param pids
     * @return
     */
    @Override
    public List<Movement> findByPids(List<Long> pids) {
        Query query = Query.query(Criteria.where("pId").in(pids));
        return mongoTemplate.find(query, Movement.class);
    }

    /**
     * 单个动态
     * @return
     */
    @Override
    public Movement findById(String movementId) {
        return mongoTemplate.findById(movementId,Movement.class);
    }
}